<template>
  <view class="recorder">
    <view class="popup">
      <u-popup mode="bottom" v-model="popShow" :border-radius="40" safe-area-inset-bottom>
        
        <view class="pop-content">
         
          <!-- 点击录音 -->
          <view class="recorder-start"  @click="start()" v-if="recording === 0">
            <view style="width:50%;display: flex;align-items: center;justify-content:center;position: absolute;" class="tips2">点击录音</view>
          </view>

          <!-- 正在录音中 -->
          <view class="recorder-end" @click="end" v-if="recording === 1" style="position: relative">
            <view style="width:100%;display: flex;align-items: center;justify-content:center;position: absolute;">
              <waveform></waveform>
              <text style="margin: 0 12rpx" v-if="showText">{{ recordTimeStr }}</text>
			  <text style="margin: 0 12rpx" v-if="!showText">识别中</text>
              <waveform></waveform>
            </view>
          </view>

        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
import waveform from './Waveform.vue'

let recorderManager = null
let innerAudioContext = null
export default {
  components:{
    waveform
  },
  props: {
    title: {
      type: String,
      default: '录制语音'
    },
    maxTime: { // 录音最大时长，单位秒
      type: Number,
      default: 15
    },
    minTime: { // 录音最小时长，单位毫秒
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      popShow: false,
      voice: null,
      timer: null, // 定时器
      recordTime: 0, // 已录制的时间
      recording: 0, // 0:未在录制，1:正在录制，2:录制完成
      playing: 0, // 0:未在播放，1:正在播放
      playTime: 0, // 已播放的时间
	  showText:true
    }
  },
  computed: {
    recordTimeStr(){
      const m = parseInt(this.recordTime / 60)
      const s = this.recordTime % 60
      return  (m < 10 ? ('0' + m) : m) + ':' + (s < 10 ? ('0' + s) : s)
    },
    playTimeStr(){
      const m = parseInt(this.playTime / 60)
      const s = this.playTime % 60
      return  (m < 10 ? ('0' + m) : m) + ':' + (s < 10 ? ('0' + s) : s)
    }
  },
  watch: {
    popShow(newVal){
      if(newVal === false){
        this.handleCancel()
      }
    }
  },
  mounted() {
	  console.log(111)
    uni.authorize({
      scope: 'scope.record',
      success: () => {
		  console.log('0000')
        recorderManager = uni.getRecorderManager()
        innerAudioContext = uni.createInnerAudioContext()
      },
	   fail: (err) => {
	      console.error('录音权限请求失败', err);
	      // 可以弹出提示框提醒用户开启权限
	      uni.showToast({
	        title: '请开启录音权限',
	        icon: 'none'
	      });
	    }
    })
  },
  methods: {
    start() {
		this.showText=true
      recorderManager.start({
        format: 'mp3',
        duration: this.maxTime * 1000
      })
      this.recording = 1
      this.timer = setInterval(() => {
        this.recordTime++
      }, 1000)

      recorderManager.onStop((res) => {
        console.log('recorder stop' + JSON.stringify(res))
        if(this.popShow === false){
          // this.recording = 0
        }
        else if (this.recordTime < this.minTime) {
          this.recording = 0
          uni.showToast({
            title: '不能小于' + this.minTime + '秒,请重新录制',
            icon: 'none'
          })
        } else {
          this.recording = 2
          this.voice = res
        }

        clearInterval(this.timer) // 清除计时器
        this.timer = null // 清除计时器
        this.recordTime = 0 // 清除计时
		
        const token = 'app-9nYLr2lKGgmGAOjvIZKTfBa3';
		const url = 'https://platformai.imaibj.cn/v1/audio-to-text'
		const header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Bearer ${token}`
          }		
		  
		  console.log(res.tempFilePath)
      uni.uploadFile({
        url: 'https://platformai.imaibj.cn/v1/audio-to-text', // 后端接口地址
        filePath: res.tempFilePath, // 本地文件路径
        name: 'file', // 后端通过这个key接收文件流
        formData: {
          'type': 'audio/mp3' // 根据文件类型选择正确的MIME类型
        },
        header: header,
        success: (uploadFileRes) => {
			
          // console.log('上传成功，响应如下：', uploadFileRes);
		  const obj = JSON.parse(uploadFileRes.data);
		  console.log(obj.text)
		  this.recording = 0
		  this.$emit('tapeText',obj.text)
		  
          // 处理上传成功的逻辑
        },
        fail: (uploadFileErr) => {
          console.error('上传失败：', uploadFileErr);
          // 处理上传失败的逻辑
        }
      });		  
		  
  //     const that = this;
  //     // 创建FormData对象
  //     //let formData = new FormData();
  //     // 读取文件并添加到formData中
  //     uni.getFileSystemManager().readFile({
  //       filePath: res.tempFilePath,
  //       encoding: 'base64',
  //       success: function (res) {
  //         //formData.append('file', res.data); // 将文件内容添加到formData中
		//   //formData.append('type', 'audio/mp3');
  //         uni.request({
  //           url: url, // 后端接口地址
  //           method: 'POST',
  //           header: header,
  //           data: {file:res.data,type:'audio/mp3'}, // 发送formData
  //           success: function (uploadFileRes) {
  //             console.log('上传成功，响应如下：', uploadFileRes);
  //             try {
  //               const result = JSON.parse(uploadFileRes.data); // 假设后端返回的是JSON格式的数据
  //               that.resultText = result.text; // 假设后端返回的文本在JSON的text字段中
  //               uni.showToast({
  //                 title: '转换成功',
  //                 duration: 2000
  //               });
  //             } catch (e) {
  //               uni.showToast({
  //                 title: '解析失败',
  //                 icon: 'none'
  //               });
  //             }
  //           },
  //           fail: function (uploadFileErr) {
  //             console.error('上传失败：', uploadFileErr);
  //             uni.showToast({
  //               title: '上传失败',
  //               icon: 'none'
  //             });
  //           }
  //         });
  //       },
  //       fail: function (err) {
  //         console.error('读取文件失败：', err);
  //         uni.showToast({
  //           title: '读取文件失败',
  //           icon: 'none'
  //         });
  //       }
  //     });
		
		
      })
    },
    end() {
		this.showText=false
      recorderManager.stop()
    },
    playVoice() {
      if (this.voice) {
        innerAudioContext.src = this.voice.tempFilePath
        innerAudioContext.play()
        this.playing = 1

        this.timer = setInterval(() => {
          this.playTime++
        }, 1000)

        innerAudioContext.onEnded(() => {
          this.stopVoice()

          uni.showToast({
            title: '播放结束',
            icon: 'none'
          })
        })
      }
    },
    stopVoice() {
      innerAudioContext.stop()

      this.playing = 0
      this.playTime = 0
      clearInterval(this.timer)
      this.timer = null
    },
    handleSubmit(){
      this.$emit('submit', this.voice)
      this.popShow = false
    },
    handleCancel(){
      this.stopVoice()
      this.voice = null

      if(this.recording === 1) {
        this.end()
      } else {
        this.recording = 0
      }

    }
  }
}
</script>

<style lang="scss" scoped>
.popup {
  .pop-header {
    height: 104rpx;
    line-height: 104rpx;
    text-align: center;
    padding: 0 32rpx;

    .icon-close {
      height: 100%;
      float: left;
    }

    .title {
      margin-left: -32rpx;
      font-size: 32rpx;
      color: #303133;
    }
  }

  .pop-content {
    //height: 520rpx;
  }
}

.recorder-start,.recorder-end,.recorder-play,.recorder-pause {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F7F8FA;
  // height: 520rpx;

  .center-container {
    text-align: center;
    margin-bottom: 24rpx;

    .tips{
      font-size: 28rpx;
      text-align: center;
      color: #999;
      margin-bottom: 24rpx;
    }

    .tips2 {
      font-size: 28rpx;
      text-align: center;
      margin-top: 24rpx;
    }
  }
}

.bottom-container{
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 96rpx;
  width: 100%;
  position: absolute;
  bottom: 24rpx;
  padding: 0 24rpx;

  .btn-box{
    display: flex;
    width: 100%;

    .btn:first-child{
      flex: 1;
      margin-right: 12rpx;
    }
    .btn:last-child{
      flex: 1;
      margin-left: 12rpx;
    }
  }
}
.recorder{
	// margin-top: 200rpx;
}
</style>
